import Food from './Food';
import ScorePanel from './ScorePanel';   
import Snake from './Snake';

class GameControl{
    //定义三个属性
    food: Food;
    scorePanel: ScorePanel;
    snake: Snake;
    //存储按键的方向
    direction: string = 'Right';
    //记录游戏是否结束
    isLive: boolean = true;
    constructor() {
        this.food = new Food();
        this.scorePanel = new ScorePanel();
        this.snake = new Snake();
        this.init()
    };
    //游戏初始化
    init() {
        //按下方向键触发
        document.addEventListener('keydown', this.keyDownHandler.bind(this))
        this.run()
    };
    keyDownHandler(event: KeyboardEvent) {
        this.direction = event.key
        // console.log(event.key);
        // console.log( this.direction );
    };
    //蛇动起来
    // ArrowUp ArrowLeft ArrowDown ArrowRight
    run() {
        //获取蛇的坐标
       let X = this.snake.X;
       let Y = this.snake.Y;
        switch (this.direction) {
            case 'ArrowUp':
            case 'Up':
                Y -= 10;
                break;
            case 'ArrowDown':
            case 'Down':
                Y += 10;
                break;
            case 'ArrowLeft':
            case 'Left':
                X -= 10;
                break;
            case 'ArrowRight':
            case 'Right':
                X += 10;
                break;
        }
        //检测是否吃到食物
        this.eat(X, Y)
        //修改蛇的坐标
       try {
        this.snake.X = X;
        this.snake.Y = Y;
       } catch (e) {
           //捕获异常，游戏结束
           alert(e)
           this.isLive = false
       }
        // setTimeout(this.run.bind(this),300)
        this.isLive && setTimeout(this.run.bind(this),300-(this.scorePanel.level-1)*30);
    };
    //判断蛇是否吃到食物
    eat(X: Number, Y: Number){
        if (X === this.food.X && Y === this.food.Y) {
            // console.log('吃到食物了');
            //蛇身体边长
            this.snake.addbodies()
            //食物位置变换
            this.food.changePosition();
            //分数增加
            this.scorePanel.addScore()
        }
        
    }
}
export default GameControl